<template>
  <!-- 顶部栏 -->
  <van-nav-bar title="修改头像" left-text="返回" left-arrow @click-left="$router.back()" placeholder fixed />
  <!-- 内容部分 -->
  <div class="user-info">
    <van-image round width="100px" height="100px" class="avatar" :src="img" />
    <span class="nickname">昵称：{{ userData.nickname }}</span>
  </div>
  <!-- 选择头像 -->
  <h2 style="text-align: center;">可选头像</h2>
  <van-grid :border="false" :column-num="3">
    <van-grid-item v-for="(item, index) in imgs" :key="index">
      <van-image :src="item" @click="changeAvatar(item)" />
    </van-grid-item>
  </van-grid>
</template>

<script setup>
import { bindUserAvatarReq, userDataReq } from '@/api/user'
import { getlocalStorage } from '@/utils/localStorage'
import { showConfirmDialog } from 'vant'
import { ref } from 'vue'
let imgs = ref([
  'http://mms1.baidu.com/it/u=1550734461,1451227155&fm=253&app=120&f=JPEG?w=800&h=800',
  'http://mms2.baidu.com/it/u=3341331339,2776642063&fm=253&app=120&f=JPEG?w=804&h=800',
  'https://shitu-query-bj.bj.bcebos.com/2025-01-11/09/c86df0a22fd8e284?authorization=bce-auth-v1%2F7e22d8caf5af46cc9310f1e3021709f3%2F2025-01-11T01%3A01%3A58Z%2F300%2Fhost%2Feb1f0fb9f742e7c9e20d1860b1ca0acf5d503de622dc2878d7c4c471e8d91a17',
  'http://mms0.baidu.com/it/u=3760501573,3345612740&fm=253&app=138&f=JPEG?w=800&h=800',
  'http://mms2.baidu.com/it/u=3110204888,1926998009&fm=253&app=138&f=JPEG?w=710&h=710',
  'http://mms1.baidu.com/it/u=1474967208,2556863795&fm=253&app=138&f=JPEG?w=500&h=500'
])
let userData = ref([])
let img = ref('')
let oldimg = ref('')
let newimg = ref('')
let userid = getlocalStorage.userid

getUserData()
async function getUserData() {
  let res = await userDataReq(userid)
  if (res.data.code == 200) {
    userData.value = res.data.data[0]
    img.value = userData.value.avatar
  }
}
function binduseravatar(item) {
  bindUserAvatarReq(userid, item)
    .then(res => {
      console.log(res.data);
      getUserData()
    })
}
function changeAvatar(item) {
  oldimg.value = img.value
  img.value = item
  newimg.value = item
  showConfirmDialog({
    title: '提示',
    message: '你要提交修改头像吗？',
  })
    .then(() => {
      binduseravatar(newimg.value)
    })
    .catch(() => {
      img.value = oldimg.value
    })
}
</script>

<style scoped>
.user-info {
  background-color: chartreuse;
  padding-top: 10px;
  display: flex;
  align-items: center;
}

.avatar {
  margin-left: 10px;
  margin-right: 50px;
}
</style>
